//
//  GoodViewController.m
//  LoveHappyShopping
//
//  Created by 白水非泉 on 16/6/23.
//  Copyright © 2016年 白水非泉. All rights reserved.
//
#define REQUESTURL @"http://zhekou.repai.com/shop/discount/api/listnew1.php?app_id=3941783725&app_oid=67341bb7a80f955a83e8e590931f70b5&app_version=1.1.1&app_channel=iphoneappstore&shce=haolemai&page=1"
#define BTNCELL @"btncell"
#define CELL @"cell"
#define HEADRER @"header"

#import "GoodViewController.h"
#import <AFNetworking.h>
#import "GoodsCategeryModel.h"
#import <UIImageView+WebCache.h>
#import "GoodsCategoryController.h"
#import "GoodsBtnViewCell.h"
#import "GoodsOptionBtnModel.h"
#import "GoodsCollectionCell.h"
#import "GoodsCollectionCellModel.h"
#import "GoodsHeaderView.h"
#import "GoodsDetailViewController.h"
#import "GoodsSearchViewController.h"

@interface GoodViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
//集合视图
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
//存放四个按钮信息的数组
@property(nonatomic,strong)NSMutableArray *categoryArray;
//存放选项按钮图片信息和url信息的数组
@property(nonatomic,strong)NSArray *optionsArray;
//阴影视图的按钮
@property(nonatomic,strong)UIButton *coverViewBtn;
//10个选项按钮所在的视图
@property(nonatomic,strong)UIView *optionBtnView;
//navgationBar的标题按钮
@property(nonatomic,strong)UIButton *navTitleBtn;
//存放集合视图的数据
@property(nonatomic,strong)NSMutableArray *goodsArray;

@end

@implementation GoodViewController
-(NSMutableArray *)categoryArray{
    if (!_categoryArray) {
        _categoryArray=[NSMutableArray array];
    }
    return _categoryArray;
}
//创建选项按钮图片和url的分类数组
-(NSArray *)optionsArray{
    if (!_optionsArray) {
        NSArray *sortNumarray=@[@"2",@"3",@"10",@"6",@"7",@"4",@"9",@"5",@"8",@"1"];
        NSArray *imgArray=@[@"nvzhuang",@"nanzhuang",@"wenyu",@"xiebao",@"peishi",@"jiaju",@"meishi",@"muying",@"meizhuang",@"shuma"];
        NSArray *textArray=@[@"女装",@"男装",@"文娱",@"鞋包",@"配饰",@"家居",@"美食",@"母婴",@"美妆",@"数码"];
        NSMutableArray *arrM=[NSMutableArray array];
        for (int i=0; i<10; i++) {
            NSMutableDictionary *dict=[NSMutableDictionary dictionary];
            [dict setValue:sortNumarray[i] forKey:@"sortNum"];
            [dict setValue:imgArray[i] forKey:@"img"];
            [dict setValue:textArray[i] forKey:@"text"];
            GoodsOptionBtnModel *model=[GoodsOptionBtnModel optionModelWithDict:dict];
            [arrM addObject:model];
        }
        _optionsArray=arrM;
    }
    return _optionsArray;
}
-(NSMutableArray *)goodsArray{
    if (!_goodsArray) {
        _goodsArray=[NSMutableArray array];
    }
    return _goodsArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavBar];
    [self registerHeaderAndCell];
    self.edgesForExtendedLayout=UIRectEdgeNone;
    [self creatOptionsBtnView];
    [self sendRequestWithUrl:REQUESTURL];
    
}
-(void)setNavBar{
    UIButton *rightbtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 21, 21)];
    [rightbtn setBackgroundImage:[UIImage imageNamed:@"search_btn"] forState:UIControlStateNormal];
    [rightbtn addTarget:self action:@selector(searchGoods) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightbtn];
    self.navigationItem.rightBarButtonItem=rightItem;
    ImgRightBtn *homeBtn=[[ImgRightBtn alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    [homeBtn setTitle:@"首页" forState:UIControlStateNormal];
    [homeBtn addTarget:self action:@selector(menuList:) forControlEvents:UIControlEventTouchUpInside];
    homeBtn.titleLabel.font=[UIFont boldSystemFontOfSize:18];
    [homeBtn setTitleColor:color(120, 110, 100) forState:UIControlStateNormal];
    [homeBtn setImage:[UIImage imageNamed:@"menu_2"] forState:UIControlStateNormal];
    [homeBtn setImage:[UIImage imageNamed:@"menu_1"] forState:UIControlStateSelected];
    self.navTitleBtn=homeBtn;
    self.navigationItem.titleView=homeBtn;
}
-(void)searchGoods{
    GoodsSearchViewController *search=[[GoodsSearchViewController alloc]init];
    [self.navigationController pushViewController:search animated:YES];
    self.hidesBottomBarWhenPushed=YES;
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];

}
//创建选项按钮视图和阴影视图
-(void)creatOptionsBtnView{
    //    创建collectionView的layout,并设置相关属性
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
    CGFloat width=(SCREENW-2*20-4*20)*0.2;
    CGFloat height=width*2+3*20;
    flowLayout.itemSize=CGSizeMake(width, width);
    flowLayout.minimumLineSpacing=20;
    flowLayout.minimumInteritemSpacing=20;
    
    CGPoint point=self.collectionView.contentOffset;
    //    创建collectionview来存放选项按钮
    UICollectionView *btnView=[[UICollectionView alloc]initWithFrame:CGRectMake(point.x, point.y, SCREENW, height) collectionViewLayout:flowLayout];
    //    设置按钮存放的内边距距离
    btnView.contentInset=UIEdgeInsetsMake(20, 20, 20, 20);
    //    为collocView注册cell的xib
    UINib *nib=[UINib nibWithNibName:@"GoodsBtnViewCell" bundle:nil];
    [btnView registerNib:nib forCellWithReuseIdentifier:BTNCELL];
    //    设置collecView的代理对象和数据源对象
    btnView.delegate=self;
    btnView.dataSource=self;
    //    设置背景颜色
    btnView.backgroundColor=[UIColor whiteColor];
    //    保存为全局变量
    self.optionBtnView=btnView;
    //    创建按钮为阴影部分
    UIButton *coverViewBtn=[[UIButton alloc]initWithFrame:CGRectMake(point.x, point.y+height, SCREENW, self.navigationController.view.bounds.size.height-132)];
    //    设置按钮背景颜色
    coverViewBtn.backgroundColor=[UIColor blackColor];
    //    设置按钮透明度
    coverViewBtn.alpha=0.3;
    //    添加按钮的点击事件实现界面的移除消失
    [coverViewBtn addTarget:self action:@selector(removeView) forControlEvents:UIControlEventTouchUpInside];
    //    将按钮界面赋值为全局变量
    self.coverViewBtn=coverViewBtn;
}
//点击阴影部分移除选项界面和阴影界面
-(void)removeView{
    self.navTitleBtn.selected=NO;
    [self.coverViewBtn removeFromSuperview];
    [self.optionBtnView removeFromSuperview];
}
//点击首页按钮实现的事件:选项按钮界面和阴影界面的显示与移除
-(void)menuList:(UIButton *)btn{
    //    点击前为未选中，实现视图的显示
    if (!btn.selected) {
        btn.selected=YES;
        [self.view addSubview:self.optionBtnView];
        [self.view addSubview:self.coverViewBtn];
    }
    //   点击前为未选中，实现视图的移除
    else{
        [self removeView];
    }
}
-(void)registerHeaderAndCell{
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize=CGSizeMake(SCREENW*0.5-5, SCREENW*0.5+60);
    flowLayout.minimumLineSpacing=10;
    flowLayout.minimumInteritemSpacing=10;
    flowLayout.sectionInset=UIEdgeInsetsMake(10, 0, 0, 0);
    flowLayout.headerReferenceSize=CGSizeMake(SCREENW, 150);
    self.collectionView.collectionViewLayout=flowLayout;
    
    UINib *headerNib=[UINib nibWithNibName:@"GoodsHeaderView" bundle:nil];
    [self.collectionView registerNib:headerNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADRER];
    
    UINib *cellNib=[UINib nibWithNibName:@"GoodsCollectionCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:CELL];
    
}-(void)sendRequestWithUrl:(NSString *)url{
    AFHTTPSessionManager *manage=[AFHTTPSessionManager manager];
    [manage GET:url parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *responseDict) {
//  [responseDict writeToFile:@"/Users/wyzc/Desktop/dict2.plist" atomically:YES];
        NSArray *categoryArr=responseDict[@"category_s"];
        for (NSDictionary *dict in categoryArr) {
            if (categoryArr.count==0) {
                break;
            }
            GoodsCategeryModel *model=[GoodsCategeryModel getModelWithDict:dict];
            [self.categoryArray addObject:model];
        }
    
        NSArray *goodsArray=responseDict[@"list"];
        for (NSDictionary *goodsDict in goodsArray) {
            GoodsCollectionCellModel *model=[GoodsCollectionCellModel cellModelWithDict:goodsDict];
            [self.goodsArray addObject:model];
        }
        [self.collectionView reloadData];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
#pragma mark - 集合视图代理方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView==self.optionBtnView) {
        return self.optionsArray.count;
    }
    else{
        return self.goodsArray.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView==self.optionBtnView) {
        GoodsOptionBtnModel *model=self.optionsArray[indexPath.row];
        GoodsBtnViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:BTNCELL forIndexPath:indexPath];
        cell.model=model;
        return cell;
    }
    else{
        GoodsCollectionCellModel *model=self.goodsArray[indexPath.row];
        GoodsCollectionCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:CELL forIndexPath:indexPath];
        cell.model=model;
        return cell;
    }
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView==self.optionBtnView) {
        GoodsOptionBtnModel *model=self.optionsArray[indexPath.row];
        [self.goodsArray removeAllObjects];
        NSString *url=[NSString stringWithFormat:@"http://zhekou.repai.com/shop/discount/api/listnew1.php?app_id=3941783725&app_oid=67341bb7a80f955a83e8e590931f70b5&app_version=1.1.1&app_channel=iphoneappstore&shce=haolemai&sort=%d&page=1",model.sortNum];
        
        [self sendRequestWithUrl:url];
        [self.navTitleBtn setTitle:model.text forState:UIControlStateNormal];
        [self removeView];
    }
    else{
        GoodsCollectionCellModel *cellModel=self.goodsArray[indexPath.row];
        GoodsDetailViewController *detailVC=[[GoodsDetailViewController alloc]init];
        detailVC.model=cellModel;
        [self.navigationController pushViewController:detailVC animated:YES];
        self.hidesBottomBarWhenPushed=YES;        
    }
}
//添加headerView
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableView=nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GoodsHeaderView *headerView=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HEADRER forIndexPath:indexPath];
        int num=0;
        for (UIButton *btn in headerView.subviews) {
            btn.tag=num;
            if (self.categoryArray.count==0) {
                break;
            }
            GoodsCategeryModel *model=self.categoryArray[num];
            NSURL *url=[NSURL URLWithString:model.pic];
            NSData *data=[NSData dataWithContentsOfURL:url];
            UIImage *img=[UIImage imageWithData:data];
            [btn setBackgroundImage:img forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            num++;
        }
        reusableView=headerView;
    }
    return reusableView;
}
-(void)btnClick:(UIButton *)btn{
    int num=(int)btn.tag;
    GoodsCategeryModel *model=self.categoryArray[num];
    GoodsCategoryController *categoryVC=[[GoodsCategoryController alloc]init];
    categoryVC.model=model;
    [self.navigationController pushViewController:categoryVC animated:YES];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
